import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:jdflutter/flutter_jdshop/config/Config.dart';
import 'package:jdflutter/flutter_jdshop/model/FocusModel.dart';
import 'package:jdflutter/flutter_jdshop/model/ProductModel.dart';
import 'package:jdflutter/flutter_jdshop/services/ScreenAdaper.dart';
class HomePage extends StatefulWidget {
  HomePage({Key? key}) : super(key: key);

  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  List _focusData=[];
  List _hotProductList = [];
  List _bestProductList = [];
  @override
  void initState(){
    super.initState();
    _getFocusData();
    _getHotProductData();
    _getBestProductData();
    print("接口返回");
  }
  // 轮播图接口请求
  _getFocusData() async{
    var api = '${Config.domain}api/focus';
    var result = await Dio().get(api);
    //print(focusData.data is Map);
    var focusList = FocusModel.fromJson(result.data);
    print(focusList.result);
    // focusList.result.forEach((value){
    //   print(value.title);
    //   print(value.pic);
    // });
    // print("接口返回 $focusList");
    setState(() {
      this._focusData = focusList.result;
    });
  }

  // 获取猜你喜欢的数据
  _getHotProductData() async{
    var api = '${Config.domain}api/plist?is_hot=1';
    var result = await Dio().get(api);
    var hotProductList = ProductModel.fromJson(result.data);
    setState(() {
      this._hotProductList = hotProductList.result;
    });
  }

  // 获取热门推荐的数据
  _getBestProductData() async{
    var api = '${Config.domain}api/plist?is_best=1';
    var result = await Dio().get(api);
    var bestProductList = ProductModel.fromJson(result.data);

    setState(() {
      this._bestProductList = bestProductList.result;
    });
  }
  //轮播图
  Widget _swiperWidget() {
    // List<Map> imgList = [
    //   {"url": "https://www.itying.com/images/flutter/slide01.jpg"},
    //   {"url": "https://www.itying.com/images/flutter/slide02.jpg"},
    //   {"url": "https://www.itying.com/images/flutter/slide03.jpg"},
    // ];
    if(this._focusData.length > 0){
    return Container(
      child: AspectRatio(
        aspectRatio: 2/1,
        child: Swiper(
            itemBuilder: (BuildContext context, int index) {
              String pic = this._focusData[index].pic;
              return new Image.network(
               // imgList[index]["url"],
                "https://jdmall.itying.com/${pic.replaceAll('\\', '/')}",
                fit: BoxFit.fill,
              );
            },
            itemCount: this._focusData.length,
            pagination: new SwiperPagination(),
            autoplay: true),
      ),
    );
    }else{
      return Text('加载中...');
    }
  }

  
  // 猜你喜欢
  Widget _hotProductListWidget(){
    if(this._hotProductList.length >0) {
      return Container(
        height: ScreenAdaper.height(234),
        padding: EdgeInsets.all(ScreenAdaper.width(20)),
        child: ListView.builder(
          scrollDirection: Axis.horizontal, // 水平
          itemBuilder: (context, index) {
            // 处理图片
            String sPic = this._hotProductList[index].sPic;
            sPic = Config.domain + sPic.replaceAll('\\', '/');
            return InkWell(
              onTap: (){
                Navigator.pushNamed(context, 'productContent',
                    arguments: {"id":this._hotProductList[index].sId}
                );
              },
              child: Column(
                children: [
                  Container(
                    height: ScreenAdaper.height(140),
                    width: ScreenAdaper.width(140),
                    margin: EdgeInsets.only(right: ScreenAdaper.width(21)),
                    child: Image.network(
                        sPic, fit: BoxFit.cover),
                  ),
                  Container(
                    padding: EdgeInsets.only(top: ScreenAdaper.height(10)),
                    height: ScreenAdaper.height(44),
                    child: Text(
                      "¥${this._hotProductList[index].price}",
                      style: TextStyle(color: Colors.red),),
                  )
                ],
              ),
            );
          },
          itemCount: 10,
        ),
      );
    }else{
      return Text("");
    }
  }

  // 推荐商品
  _recProductItemWidget(){
    var itemWidth = (ScreenAdaper.getScreenWidth() - 30)/2;
    return Container(
      padding: EdgeInsets.all(10),
      child: Wrap(
        runSpacing: 10,
        spacing: 10,
        children: this._bestProductList.map((value){
          // 图片
          String sPic = value.sPic;
          sPic=Config.domain+sPic.replaceAll('\\', '/');
          return InkWell(
            onTap: (){
              Navigator.pushNamed(context, '/productContent',
                  arguments: {"id": value.sId});
            },
            child: Container(
              padding: EdgeInsets.all(10),
              width: itemWidth,
              decoration: BoxDecoration(
                  border: Border.all(color: Color.fromRGBO(233, 233, 233, 0.9),width: 1)
              ),
              child: Column(
                children:<Widget> [
                  Container(
                    width: double.infinity, // ??
                    child: AspectRatio(  // ?? /防止服务器返回的图片大小不一致导致高度不一致问题
                      aspectRatio: 1/1,
                      child: Image.network( '${sPic}',
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                  Padding(padding: EdgeInsets.only(top: ScreenAdaper.height(20)),
                    child: Text(
                      "${value.title}",
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: Colors.black54),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: ScreenAdaper.height(20)),
                    child: Stack(
                      children: <Widget>[
                        Align(alignment: Alignment.centerLeft,
                          child: Text("¥${value.price}",style: TextStyle(color: Colors.red,fontSize: 16),),
                        ),
                        Align(
                          alignment: Alignment.centerRight,
                          child: Text("¥${value.oldPrice}",
                            style: TextStyle(color: Colors.black54,fontSize: 14,decoration: TextDecoration.lineThrough),),

                        )
                      ],
                    ),

                  )
                ],
              ),
            ),
          );
        }).toList(),
      ),
    );

  }

  Widget _titleWidget(value) {
    return Container(
      //height:ScreenUtil().setHeight(34),
      height: ScreenAdaper.height(32),
      margin: EdgeInsets.only(left:ScreenAdaper.width(20)),
     // margin: EdgeInsets.only(left: 20),
     // padding: EdgeInsets.only(left:20),
      padding: EdgeInsets.only(left: ScreenAdaper.height(20)),
      decoration: BoxDecoration(
          border: Border(
              left: BorderSide(
                color: Colors.red,
                width: ScreenAdaper.width(10)
              )
          )
      ),
      child: Text(value,style: TextStyle(
          color: Colors.black54,
          fontSize: ScreenAdaper.size(24)
        //fontSize: 20,
      ),),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        _swiperWidget(),
        SizedBox(height: ScreenAdaper.height(12)),
        _titleWidget("猜你喜欢"),
        SizedBox(height: ScreenAdaper.height(12)),
        _hotProductListWidget(),
        SizedBox(height: ScreenAdaper.height(12)),
        _titleWidget("热门推荐"),
        _recProductItemWidget()


      ],
    );
  }
}
